package net.jeeframework.fileuplod.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeeframework.fileuplod.util.FileSystemConfig;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileViewServlet extends HttpServlet {

	private static final long serialVersionUID = -8571173811688494824L;

	private static final Log log = LogFactory.getLog(FileViewServlet.class);

	private enum FileType {
		jpeg, jpg, gif, png, bmp, swf, mp3, wma, wmv, flv;
	}

	private void setContentType(HttpServletResponse resp, String type) {
		FileType fileType = Enum.valueOf(FileType.class, type.toLowerCase());
		switch (fileType) {
		case jpeg:
		case jpg:
			resp.setContentType("image/jpeg");
			break;
		case gif:
		case png:
		case bmp:
			resp.setContentType("image/" + type);
			break;
		case swf:
			resp.setContentType("application/x-shockwave-flash");
			break;
		case mp3:
			resp.setContentType("audio/mp3");
			break;
		case wma:
			resp.setContentType("audio/x-ms-wma");
			break;
		case wmv:
			resp.setContentType("video/x-ms-wmv");
			break;
		case flv:
			resp.setContentType("video/x-flv");
			break;
		default:
			break;
		}
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {

			String id = request.getParameter("id");

			long sMillis = System.currentTimeMillis();
			log.debug("%%%%% 开始处理图片请求[" + sMillis + "|id=" + id + "]");

			String extension = FilenameUtils.getExtension(id);
			setContentType(response, extension);
			InputStream in = new FileInputStream(FileSystemConfig.getConfig().getString("base.save.dir") + File.separator + id);
			OutputStream out = response.getOutputStream();
			byte[] readBytes = new byte[1024];
			int readLength = in.read(readBytes);
			while (readLength != -1) {
				out.write(readBytes, 0, readLength);
				out.flush();
				readLength = in.read(readBytes);
			}
			in.close();
			out.close();

			response.flushBuffer();

			long eMillis = System.currentTimeMillis();
			long castMillis = eMillis - sMillis;
			log.debug("--> 图片请求处理结束[" + eMillis + "|耗时: " + castMillis + "]");
		} catch (Exception e) {
			log.error("--> 图片请求处理异常:", e);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
